package com.linln.admin.store.controller;

import com.linln.admin.store.validator.StoreTypeValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.*;
import com.linln.common.vo.ResultVo;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.store.domain.Type;
import com.linln.modules.store.service.TypeService;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("/store/type")
public class StoryTypeController {

    @Autowired
    private TypeService typeService;

    /**
     * 跳转到列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("store:type:index")
    public String index(Model model) {
        String search = HttpServletUtil.getRequest().getQueryString();
        model.addAttribute("search", search);
        return "/store/type/index";
    }

    /**
     * 部门数据列表
     */
    @GetMapping("/list")
    @RequiresPermissions(value = {"store:type:index", "store:type:index"}, logical = Logical.OR)
    @ResponseBody
    public ResultVo list(Type type) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("title", match -> match.contains());
        // 获取部门列表
        Example<Type> example = Example.of(type, matcher);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<Type> list = typeService.getListByExample(example, sort);
        return ResultVoUtil.success(list);
    }
    
    
    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("store:type:add")
    public String toAdd() {
        return "/store/type/add";
    }


    /**
     * 跳转到添加子页面
     */
    @GetMapping("/addSon/{pid}")
    @RequiresPermissions("message:type:addSon")
    public String toAddSon(@PathVariable Long pid, Model model) {
        model.addAttribute("pid", pid);
        return "/store/type/addSon";
    }
    
    
    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("store:type:edit")
    public String toEdit(@PathVariable("id") Type type, Model model) {
        model.addAttribute("type", type);
        return "/store/type/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"store:type:add", "store:type:edit"})
    @ResponseBody
    public ResultVo save(@Validated StoreTypeValid valid, Type type) {
        // 复制保留无需修改的数据
        
        if (type.getId() == null) {
            // 排序为空时，添加到最后
            if(type.getNum() == null){
                Integer sortMax = typeService.getSortMax(type.getPid());
                type.setNum(sortMax !=null ? sortMax - 1 : 0);
            }
        }

        // 添加/更新全部上级序号
        if (type.getPid()!=null && type.getPid() != 0) {
        	Type pDept = typeService.getById(type.getPid());
            type.setPids(pDept.getPids() + ",[" + type.getPid() + "]");
        } else {
       	 type.setPids("[0]");
        }

        // 将验证的数据复制给实体类
        if (type.getId() != null) {
        	Type beDept = typeService.getById(type.getId());
            EntityBeanUtil.copyProperties(beDept, type, "type");
        }
        // 保存数据
        typeService.save(type);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("store:type:detail")
    public String toDetail(@PathVariable("id") Type type, Model model) {
        model.addAttribute("type",type);
        return "/store/type/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("store:type:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (typeService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}